package com.example.demo.thread;

/**
 * @author: htc
 * @date: Created in 17:33 2019/1/2.
 */
public class TraditionalThreadSynchronized {

    class Outputer {
        /**
         * 没有实现原子性
         *
         * @param name
         */
        public void output(String name) {
            for (int i = 0; i < name.length(); i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }

        /**
         * 实现原子性
         * Synchronized 要锁定共享的对象资源
         */
        public synchronized void outputSynchronized(String name) {
            synchronized (name) {
                for (int i = 0; i < name.length(); i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
        }
    }

    private void init() {
        Outputer outputer = new Outputer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output("hutingcong");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output("liuhailing");
                }
            }
        }).start();
    }


    private void init2() {
        Outputer outputer = new Outputer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.outputSynchronized("hutingcong");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.outputSynchronized("liuhailing");
                }
            }
        }).start();
    }


    /**
     * 静态方法中不能new内部类实例对象
     *
     * @param args
     */
    public static void main(String[] args) {
//        new TraditionalThreadSynchronized().init();
        new TraditionalThreadSynchronized().init2();
    }
}
